﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DT = CPPEI.Coolzon.Designtime.Metadata;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// 发布方案到文件系统的线程
    /// </summary>
    public static class PublishToFileSystemThread
    {
        private static bool s_isRunning;
        private static Thread s_thread;

        private static string s_solutionDir;
        private static string s_targetDir;
        private static DT.Solution s_solution;
        private static Action<bool> action_complated;

        /// <summary>
        /// 开始发布
        /// </summary>
        /// <param name="solutionDir">方案所在的目录</param>
        /// <param name="solution">方案对象</param>
        /// <param name="targetDir">发布到目标目录</param>
        /// <param name="complated">是否发布成功</param>
        public static void Start(string solutionDir, DT.Solution solution, string targetDir,
            Action<bool> complated)
        {
            if(s_isRunning)
            {
                return;
            }

            s_solution = solution;
            s_targetDir = targetDir;
            s_solutionDir = solutionDir;
            action_complated = complated;

            s_isRunning = true;
            s_thread = new Thread(Running);
            s_thread.Start();
        }

        public static void Stop()
        {
            if (s_isRunning && s_thread == null)
            {
                s_isRunning = false;
                s_thread.Abort();
                s_thread = null;
                if (action_complated != null)
                {
                    action_complated(false);
                }
            }
        }

        private static void Running()
        {
            bool isSuccess = false;
            DT.Publisher publisher = new DT.Publisher();
            if (publisher.Publish(s_solution, s_solutionDir, s_targetDir))
            {
                if (DT.PackageUtil.Compress(s_targetDir + s_solution.Name + ".zip", s_targetDir + s_solution.ID + "\\"))
                {
                    System.IO.Directory.Delete(s_targetDir + s_solution.ID + "\\", true);
                    isSuccess = true;
                }
            }

            if (s_isRunning && action_complated != null)
            {
                action_complated(isSuccess);
            }
            s_isRunning = false;
            s_thread = null;
        }
    }
}
